package com.boruan.shengtangfeng.core.service.impl;

import java.util.Date;
import java.util.List;

import com.boruan.shengtangfeng.core.dao.ISystemUserDao;
import com.boruan.shengtangfeng.core.entity.SystemUser;
import com.boruan.shengtangfeng.core.service.ISystemUserService;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.boruan.shengtangfeng.core.utils.Digests;
import com.boruan.shengtangfeng.core.utils.Encodes;
import com.boruan.shengtangfeng.core.utils.Global;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.UserUtil;

/**
 * @author: lihaicheng
 * @Description:
 * @date:2020年3月10日 上午11:14:10
 */
@SuppressWarnings("all")
@Service
@Transactional(readOnly = true)
public class SystemUserService implements ISystemUserService {
	private static Logger logger = LoggerFactory.getLogger(UserService.class);
	@Autowired
	private ISystemUserDao systemUserDao;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	/**
	 * 根据手机号查询
	 */
	@Override
	public SystemUser findByMobile(String mobile) {
		return systemUserDao.findByMobile(mobile);
	}

	/**
	 * 根据id查询
	 */
	@Override
	public SystemUser findById(Long id) {
		return systemUserDao.unique(id);
	}

	@Override
	@Transactional(readOnly = false)
	public boolean save(SystemUser systemUser, Long roleId) {
		try {
			if (systemUser.getId() == null) {

				systemUser.setCreateTime(new Date());
				this.entryptPassword(systemUser);
				KeyHolder kh = systemUserDao.insertReturnKey(systemUser);
				// 添加权限
				if (roleId != null) {
					systemUserDao.insertRole(kh.getLong(), roleId);
				}
				systemUser.setId(kh.getLong());
			} else {
				systemUserDao.updateById(systemUser);
			}
		} catch (Exception e) {
			logger.error("添加系统用户失败，错误原因：{}", e.getMessage());
			return false;
		}
		return true;
	}

	@Override
	@Transactional(readOnly = false)
	public void saveWithPassword(SystemUser systemUser) {
		systemUser.setSalt(UserUtil.getSalt());
		systemUser.setPassword(UserUtil.entryptPassword(systemUser.getPassword(), systemUser.getSalt()));
		if (systemUser.getId() == null) {
			systemUser.setCreateTime(new Date());
			this.entryptPassword(systemUser);
			KeyHolder kh = systemUserDao.insertReturnKey(systemUser);
			systemUser.setId(kh.getLong());
		} else {
			systemUserDao.updateById(systemUser);
		}
	}

	/**
	 * @author: lihaicheng
	 * @Description: 分页获取
	 * @date:2020年3月10日 上午11:14:10
	 **/
	@Override
	public void pageQuery(PageQuery<SystemUser> query, SystemUser systemUser) {
		query.setParas(systemUser);
		systemUserDao.pageQuery(query);
	}

	public void pageSystemUser(PageQuery<SystemUser> query , SystemUser systemUser){
		query.setParas(systemUser);
		systemUserDao.pageSystemUser(query);
	}
	/**
	 * @author: lihaicheng
	 * @Description: 删除
	 * @date:2020年3月10日 上午11:14:10
	 **/
	@Override
	@Transactional(readOnly = false)
	public GlobalReponse delete(Long id) {
		try {
//			SystemUser systemUser = systemUserDao.unique(id);
//			systemUser.setIsDeleted(true);
//			systemUser.setUpdateTime(new Date());
//			systemUserDao.updateById(systemUser);
			systemUserDao.deleteById(id);
		} catch (Exception e) {
			e.printStackTrace();
			GlobalReponse.fail();
		}
		return GlobalReponse.success();
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(SystemUser systemUser) {
		byte[] salt = Digests.generateSalt(Global.SALT_SIZE);
		systemUser.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(systemUser.getPassword().getBytes(), salt, Global.HASH_INTERATIONS);
		systemUser.setPassword(Encodes.encodeHex(hashPassword));
	}

	/**
	 * @author: lihaicheng
	 * @Description: 后台获取全部加盟商
	 * @date:2020年3月10日 上午11:14:10
	 **/
	@Override
	public List<SystemUser> findAll() {
		return systemUserDao.findAll();

	}

	@Override
	public SystemUser findId(Long id) {
		return systemUserDao.unique(id);
	}

	/**
	 * @author: lihaicheng
	 * @Description: 管理员修改密码
	 * @date:2020年3月10日 上午11:14:10
	 **/
	@Override
	@Transactional(readOnly = false)
	public GlobalReponse changePassword(SystemUser user, String oldPassword, String password) {
		if (UserUtil.match(oldPassword, user.getPassword(), user.getSalt())) {
			user.setSalt(UserUtil.getSalt());
			user.setPassword(UserUtil.entryptPassword(password, user.getSalt()));
			systemUserDao.updateById(user);
			return GlobalReponse.success();
		} else {
			return GlobalReponse.fail("旧密码错误");
		}
	}

	@Override
	public SystemUser findUserAndRole(Long id) {
		return systemUserDao.findUserAndRole(id);
	}

	@Override
	@Transactional(readOnly = false)
	public void deleteUserRole(Long userId) {
		systemUserDao.deleteUserRole(userId);
	}

	@Override
	@Transactional(readOnly = false)
	public Boolean updateUserRole(SystemUser user, List<Long> roleIds) {
		systemUserDao.deleteUserRole(user.getId());
		if (!roleIds.isEmpty()) {
			for (Long roleId : roleIds) {
				systemUserDao.insertUserRole(user.getId(), roleId);
			}
		}
		return true;
	}

	@Override
	public List<SystemUser> findByEmployeeNumberOrName(String assistantNo, String assistantName) {
		List<SystemUser> list = systemUserDao.findByEmployeeNumberOrName(assistantNo, assistantName);
		return list;
	}

    @Override
    public SystemUser findByLoginName(String loginName) {
        return systemUserDao.findByLoginName(loginName);
    }

}
